package com.itfreer.arcgis.layer;

import android.app.Activity;
import android.view.MotionEvent;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.IdentifyLayerResult;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.itfreer.arcgis.draw.DrawToolManager;
import com.itfreer.arcgis.utils.MapUtils;
import com.itfreer.gis.datasyn.entity.ProjectEntity;
import com.itfreer.utils.common.LogUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 地图选择器
 */
public class LayerSelect {

    public static final LayerSelect instance = new LayerSelect();
    private LayerSelect() {
    }

//    private ProgressDialog loginDialog;
    /**
     * 当前选择的图层
     */
    private FeatureLayer selectedFeatureLayer = null;
    /**
     * 当前选择的要素集
     */
    private List<Feature> selectedFeatures = new ArrayList<>();

    /**
     * 获取当前选择的图层
     * @return
     */
    public FeatureLayer getSelectedFeatureLayer() {
        return selectedFeatureLayer;
    }

    /**
     * 获取选择的要素
     * @return
     */
    public List<Feature> getSelectedFeatures() {
        return selectedFeatures;
    }

    /**
     * 点选要素
     * 1）、可见，可选择图层为选择图层集；
     * 2）、第一个选择图层开始选择，选中则不在处理，选不中，则继续选择。
     */
    public void select(final Activity main, final MapView mMapView) {
        // 图层配置
        final List<FeatureLayer> featureLayers = MapUtils.GetFeatureLayers(mMapView);
        if (featureLayers == null || featureLayers.size() == 0) {
            return;
        }

        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(main, mMapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e)
            {
                if(DrawToolManager.GetCurrentTool() ==null || !DrawToolManager.GetCurrentTool().hasDraw())
                {
                    //                loginDialog = ProgressDialog.show(main, "要素选择", "请等待...", true, false);
                    final android.graphics.Point screenPoint = new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY()));
                    // 异步处理
                    new Thread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            select(screenPoint, mMapView);
                        }
                    }).start();

                }
                return true;
            }
        });
    }

    private void select(android.graphics.Point screenPoint, final MapView mMapView){
        clear();
        final ListenableFuture<List<IdentifyLayerResult>> identifyLayerResultsFuture = mMapView.identifyLayersAsync(screenPoint,12,false,1);
        identifyLayerResultsFuture.addDoneListener(new Runnable() {
            @Override
            public void run() {
                try {
                    List<IdentifyLayerResult> identifyLayerResults = identifyLayerResultsFuture.get();
                    for (IdentifyLayerResult identifyLayerResult : identifyLayerResults) {
                        FeatureLayer sLayer = (FeatureLayer)identifyLayerResult.getLayerContent();
                        Feature sFeature = (Feature)identifyLayerResult.getElements().get(0);

                        ProjectEntity config = LayerLoader.instance.getConfig(sLayer);
                        if(config.getShow() != null
                                && config.getShow() == true
                                && config.getCanSelect() != null
                                && config.getCanSelect() == true){
                            selectedFeatureLayer = sLayer;
                            selectedFeatures.add(sFeature);
                            selectedFeatureLayer.selectFeature(sFeature);

//                            if (loginDialog!=null){
//                                loginDialog.dismiss();
//                                loginDialog = null;
//                            }
                            return;
                        }
                    }
                } catch (InterruptedException | ExecutionException e) {
                    LogUtils.Print("Error identifying results: " + e.getMessage(), LogUtils.Lever.Error);
                }

//                if (loginDialog!=null){
//                    loginDialog.dismiss();
//                    loginDialog = null;
//                }
            }
        });
    }

    /**
     * 取消选择
     * @param mMapView
     */
    public void unSelect(Activity main,  MapView mMapView) {
        clear();

        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(main, mMapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                return super.onSingleTapConfirmed(e);
            }
        });
    }

    /**
     * 清除
     */
    private void clear(){
        if(selectedFeatureLayer!=null){
            MapUtils.UnSelectFeature(selectedFeatureLayer, selectedFeatures);
        }
        selectedFeatureLayer = null;
        selectedFeatures.clear();
    }
}
